# -*- coding: utf-8 -*-
import time,md5,re,os, random

def fbuffer(f, chunk_size=10000):
    while True:
      chunk = f.read(chunk_size)
      if not chunk: break
      yield chunk
      
         
def upload_file(form, form_item,PATH_TO_UPLOAD):    
    if form_item in form:
        fileitem = form[form_item]
        if fileitem.filename:
            if not os.path.isdir( PATH_TO_UPLOAD):
                os.mkdir(PATH_TO_UPLOAD)
            ff = os.path.basename(fileitem.filename)
            rr = re.findall('^.*?(\.\w{1,4})$',str(ff))
            if rr:
                newFileName = md5.new(str(time.time())).hexdigest() + rr[0]
                newWebPath =  PATH_TO_UPLOAD + newFileName
                newfilePATH = PATH_TO_UPLOAD + newFileName
                f = open(newfilePATH, 'wb', 10000)
                for chunk in fbuffer(fileitem.file): f.write(chunk)
                f.close()
                r = {'name':newFileName,'web':newWebPath,'path':newfilePATH}
                return r
            
            
def multi_upload(req, form, key, PATH_TO_UPLOAD):
    data = []
    
    def go(fileitem):       
        if fileitem.filename:
            if not os.path.isdir( PATH_TO_UPLOAD):
                os.mkdir(PATH_TO_UPLOAD)
            ff = os.path.basename(fileitem.filename)
            rr = re.findall('^.*?(\.\w{1,4})$',str(ff))
            
            if rr:                
                newFileName = md5.new( str(time.time() + random.random() ) ).hexdigest() + rr[0]
                newWebPath =  PATH_TO_UPLOAD + newFileName
                newfilePATH = PATH_TO_UPLOAD + newFileName
                f = open(newfilePATH, 'wb', 10000)
                for chunk in fbuffer(fileitem.file): 
                    f.write(chunk)
                f.close()
                return [PATH_TO_UPLOAD + newFileName, newFileName]
        
    

    if isinstance(req.form['Filedata'], list):
        for file in req.form['Filedata']:        
            data.append( go(file)  )
    else:
        data.append( go(req.form['Filedata'])  )
        
        
        
    return data